package cn.study.concurrenttools.cylicbarrier;

import java.util.concurrent.*;

/**
 * @Author     ：跟大佳一起学架构
 * @Description：CyclicBarrier 黑车司机拉人
 */
public class CyclicBarrierDemo {
    private static ExecutorService executorService = Executors.newFixedThreadPool(4);

    public static void main(String[] args) throws InterruptedException {
        CyclicBarrier cyclicBarrier = new CyclicBarrier(4, () -> System.out.println("人齐了，准备发车"));

        for (int i = 0; i < 12; i++) {
            final int id = i + 1;
            executorService.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        int sleepMills = ThreadLocalRandom.current().nextInt(2000);
                        Thread.sleep(sleepMills);
                        System.out.println(id + "号到了，上车");
                        cyclicBarrier.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }catch(BrokenBarrierException e){
                        e.printStackTrace();
                    }
                }
            });

        }
        System.out.println("主程序完成");
    }
}



//            new Thread(new Runnable() {
//                @Override
//                public void run() {
//                    try {
//                        int sleepMills = ThreadLocalRandom.current().nextInt(2000);
//                        Thread.sleep(sleepMills);
//                        System.out.println(id + "号到了，上车");
//                        cyclicBarrier.await();
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    } catch (BrokenBarrierException e) {
//                        e.printStackTrace();
//                    }
//                }
//            }
//            ).start();

